package com.nsqt.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期处理
 */
public class DateUtils {
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private final static Logger logger = LoggerFactory.getLogger(DateUtils.class);

    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date) {
        return date2Str(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
     *
     * @param date
     * @return
     */
    public static Date str2Date(String date) {
        if (!date.equals("")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        } else {
            return null;
        }
    }

    /**
     * 按照参数format的格式，日期转字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String date2Str(Date date, String format) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        } else {
            return "";
        }
    }

    /**
     * 计算距离现在多久，非精确
     *
     * @param date
     * @return
     */
    public static String getTimeBefore(Date date) {
        Date now = new Date();
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String r = "";
        if (day > 0) {
            r += day + "天";
        } else if (hour > 0) {
            r += hour + "小时";
        } else if (min > 0) {
            r += min + "分";
        } else if (s > 0) {
            r += s + "秒";
        }
        r += "前";
        return r;
    }

    /**
     * 计算距离现在多久，精确
     *
     * @param date
     * @return
     */
    public static String getTimeBeforeAccurate(Date date) {
        Date now = new Date();
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String r = "";
        if (day > 0) {
            r += day + "天";
        }
        if (hour > 0) {
            r += hour + "小时";
        }
        if (min > 0) {
            r += min + "分";
        }
        if (s > 0) {
            r += s + "秒";
        }
        r += "前";
        return r;
    }

    /**
     * 获取上月第一天1号
     */
    public static String getLastMonthFirstDay() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String lastMonth = format.format(m);
        String res = lastMonth.substring(0, 8) + "01";
        return res;
    }

    /**
     * 获取上月最后一天
     */
    public static String getLastMonthLastDay() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DATE, -1);
        Date m = calendar.getTime();
        String res = format.format(m);

        return res;
    }

    /**
     * 获取当月1号
     */
    public static String getCurrMonthDayOne() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        Date m = c.getTime();

        String lastMonth = format.format(m);
        String res = lastMonth.substring(0, 8) + "01";
        return res;
    }

    public static int dayOfWeek(Date date) {

        Calendar now = Calendar.getInstance();
//一周第一天是否为星期天
        boolean isFirstSunday = (now.getFirstDayOfWeek() == Calendar.SUNDAY);
//获取周几

//若一周第一天为星期天，则-1
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(date);
        int weekDay = aCalendar.get(Calendar.DAY_OF_WEEK);
        if (isFirstSunday) {
            weekDay = weekDay - 1;
            if (weekDay == 0) {
                weekDay = 7;
            }
        }

        return weekDay;
    }

    public static Date getNextDate(Date date, int index, boolean flag) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);// 获得当前时间
        if (flag) {
// 日期不变，把时间设定为00：00：00
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 00);
            cal.set(Calendar.SECOND, 00);
        }
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) + index);
        return cal.getTime();
    }

    public static Date getDate(Date currentDate, int days) {
        /*
         * 1，根据传入日期获取下一天日期
         * 2，判断下一天日期是否为工作日，如果是则设置下一次循环日期为此日期
         * 如果不为工作日，为周6，日期前进2天，为周天前进1天
         * 3, 获取指定天数后的工作日
         */
        Date date = currentDate;
        int month = date.getMonth();

        /* 设置循环次数
         * 如果含最后一天则循环 days + 1 天，不需要含最后一天，则循环 days次
         * */
        for (int i = 0; i < days; i++) {
            Date nextDate = getNextDate(date, 1, false); //获取下一天的日期
            int weekDay = dayOfWeek(nextDate); //下一天日期为星期几
            if (weekDay == 6) { //为星期六
                date = getNextDate(date, 3, false);
            } else if (weekDay == 7) { //为星期天
                date = getNextDate(date, 2, false);
            } else {
                date = nextDate;
            }
        }
        int newMonth = date.getMonth();
        //元旦，加一天
        if (month > 10 && newMonth == 1) {
            return getNextDate(date, 1, false);
        }
        //春节，加三天
        if (month == 1 && newMonth == 2) {
            return getNextDate(date, 3, false);
        }
        //春节，加三天
        if (month == 12 && newMonth == 2) {
            return getNextDate(date, 3, false);
        }
        //清明，加一天
        if (month < 4 && newMonth == 4) {
            return getNextDate(date, 1, false);
        }
        //五一，加一天
        if (month < 5 && newMonth == 5) {
            return getNextDate(date, 1, false);
        }
        //国庆中秋，加四天
        if (month < 10 && newMonth == 10) {
            return getNextDate(date, 4, false);
        }
        return date;
    }

    /**
     * 根据开始日期 ，需要的工作日天数 ，计算工作截止日期，并返回截止日期
     *
     * @param startDate 开始日期
     * @param workDay   工作日天数(周一到周五)
     * @author 【狒狒：Q97175234】
     * @time 2015-11-23 上午9:21:25
     * @motto 既然笨到家，就要努力到家...
     */

    public static Date getWorkDay(Date startDate, int workDay) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(startDate);
        for (int i = 0; i < workDay; i++) {
            c1.set(Calendar.DATE, c1.get(Calendar.DATE) + 1);
            if (Calendar.SATURDAY == c1.get(Calendar.SATURDAY) || Calendar.SUNDAY == c1.get(Calendar.SUNDAY)) {
                workDay = workDay + 1;
                c1.set(Calendar.DATE, c1.get(Calendar.DATE) + 1);
                continue;
            }
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df.format(c1.getTime()) + " " + getWeekOfDate(c1.getTime()));
        return c1.getTime();
    }

    /**
     * 根据日期，获取星期几
     *
     * @param dt
     * @return String类型
     * @author 【狒狒：Q9715234】
     * @time 2015-11-23 上午9:21:25
     * @motto 既然笨到家，就要努力到家...
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) w = 0;
        return weekDays[w];
    }

    public static void main(String[] args) {

        System.out.println(DateUtils.getLastMonthFirstDay());
        System.out.println(DateUtils.getLastMonthLastDay());
    }
}
